﻿using Autofac;

namespace MyPetHub.Common
{
    public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // InstancePerLifetimeScope 同一个Lifetime生成的对象是同一个实例
            // SingleInstance 单例模式，每次调用，都会使用同一个实例化的对象；每次都用同一个对象
            // InstancePerDependency 默认模式，每次调用，都会重新实例化对象；每次请求都创建一个新的对象

            // The generic ILogger<TCategoryName> service was added to the ServiceCollection by ASP.NET Core.
            // It was then registered with Autofac using the Populate method. All of this starts
            // with the `UseServiceProviderFactory(new AutofacServiceProviderFactory())` that happens in Program and registers Autofac
            // as the service provider.

            //当前程序集中查找约定注入
            builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces().InstancePerLifetimeScope(); 

            //业务逻辑程序集
            var interfaceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("BusinessLogic"));
            var implementedAssembly = interfaceAssembly; //System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("BusinessLogic"));

            builder.RegisterAssemblyTypes(interfaceAssembly, implementedAssembly).Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces().InstancePerLifetimeScope();

            //泛型实现
            //builder.Register(c => new ValuesService(c.Resolve<ILogger<ValuesService>>()))
            //    .As<IValuesService>()
            //    .InstancePerLifetimeScope();

            //builder.RegisterType<MyTest>().As<IMyTest>();
        }
    }
}
